<template>
	<view class="root">
		<unicloud-db ref="udb" @load="onLoadedData" :where="dbWhere" orderby="create_time desc"
			v-slot:default="{data, loading, error, options,hasMore}" :collection="dbCollection">
			<view v-if="error">{{error.message}}</view>
			<view v-else>
				<view v-if="model == 'notice-bar'" class="uni-notice-bar">
					<template v-if="notificationList.length">
						<uni-icons type="sound" :size="22" color="#fd8734"></uni-icons>
						<swiper class="swiper" :circular="true" :vertical="true" :autoplay="true" :interval="3000">
							<swiper-item @click="clickSwiperItem(item)" v-for="(item,index) in notificationList" :key="index">
								<text class="swiper-item">{{item.title || item.content}}</text>
							</swiper-item>
						</swiper>
						<text @click="showMore" class="show-more">[查看更多]</text>
					</template>
				</view>
				<template v-else>
					<uni-collapse class="main-container" v-if="notificationList.length" @change="change" :accordion="true">
						<uni-collapse-item v-for="(item,index) in notificationList" :key="index">
							<template v-slot:title>
								<view class="main-container-item">
									<view class="dot-box">
										<uni-badge :text="item.is_read?'':'1'" :is-dot="true" size="small"></uni-badge>
									</view>
									<text v-if="isWidescreen" class="item-type" space="emsp">{{types[item.type_code/100].text}}   </text>
									<view class="title-box">
										<text>{{item.title||item.content.slice(0,20)+'...'}}</text>
										<uni-dateformat :date="item.create_time" format="yyyy-MM-dd hh:mm" class="dateformat"></uni-dateformat>
									</view>
								</view>
							</template>
							<view class="content">
								<text class="text">{{item.content}}</text>
							</view>
						</uni-collapse-item>
					</uni-collapse>
					<uni-load-more :status="hasMore?'loading':'noMore'"></uni-load-more>
				</template>
			</view>
		</unicloud-db>
		<uni-segmented-control v-if="model == 'list'" :current="currentIndex" :values="types" style-type="text" active-color="#42b983"
			class="segmented-control" @clickItem="onClickSegmentedControl" />
	</view>
</template>

<script>
	const db = uniCloud.database();
	const dbCmd = db.command
	import uncUtils from '@/uni_modules/uni-notification-center/utils/main.js';
	export default {
		props: {
			model: {
				type: String,
				default(){
					return 'list'
				}
			},
		},
		data() {
			return {
				types: [{
						text: '全部',
						badge: 0
					},
					{
						text: '平台通知',
						badge: 0
					},
					{
						text: '财务通知',
						badge: 0
					},
					{
						text: '审核通知',
						badge: 0
					}
				],
				currentIndex: 0,
				notificationList: [],
				isWidescreen:false
			}
		},
		computed: {
			dbWhere() {
				if(this.model == 'list'){
					uni.showLoading({
						title: '加载中...',
						mask: true
					});
				}
				
				let dbWhere = `("user_id" == $cloudEnv_uid || "to_all" == true)`
				if (this.currentIndex) {
					dbWhere += `&& "type_code" == ${this.currentIndex * 100}`
				}
				return dbWhere
			},
			dbCollection(){
				return [
					db.collection('uni-notification-center').where(this.dbWhere).getTemp(),
					db.collection('uni-notification-read-log')
						.where('"user_id" == $cloudEnv_uid')
						.getTemp()
				]
			}
		},
		beforeMount() {
			uncUtils.init()
		},
		async mounted() {
			// #ifdef H5
			const mediaQueryOb = uni.createMediaQueryObserver(this)
			mediaQueryOb.observe({
				minWidth: 960
			}, matches => {
				this.isWidescreen = matches
			})
			// #endif
			
			this.types.forEach((item,index)=>{
				uncUtils.bindUnreadCount(unreadCount=>{
					this.types[index].badge = unreadCount
				},index*100)
			})
			// console.log('this.types',this.types);
			uni.onPushMessage(res=>{
				if(res.data.payload.type == 'uni-notification-center'){
					this.refresh()
					this.notificationList.unshift(res.data.payload)
				}
			})
		},
		methods: {
			onLoadedData(data) {
				data.forEach(item=>{
					if(item.to_all){
						item.is_read = (item._id['uni-notification-read-log'].length != 0)
					}
					item._id = item._id._value
				})
				this.notificationList = data
				// console.log('aalll',this.notificationList);
				
				if(this.model == 'list'){
					uni.hideLoading()
				}
			},
			onClickSegmentedControl({
				currentIndex
			}) {
				this.currentIndex = currentIndex
			},
			change(e) {
				if (e) {
					let index = parseInt(e)
					let item = this.notificationList[index]
					if(!item.is_read){
						item.is_read = true
						console.log(item,item.type_code);
						// console.log('uncUtils.unreadCounts[item.type_code]',uncUtils.unreadCounts[item.type_code]);
						let unreadCounts = uncUtils.unreadCounts
						unreadCounts[item.type_code] --
						uncUtils.unreadCounts = unreadCounts
						
						// 群发的
						if(item.to_all){
							// console.log('uncUtils.unreadCounts[item.type_code]',uncUtils.unreadCounts[item.type_code]);
							db.collection('uni-notification-read-log')
							.add({
								"user_id":uniCloud.getCurrentUserInfo().uid,
								"notification_id":item._id
							}).catch(e => {
								console.error(e);
							})
						}else{
							// console.log('uncUtils.unreadCounts[item.type_code]',uncUtils.unreadCounts[item.type_code]);
							db.collection('uni-notification-center')
							.doc(item._id)
							.update({
								is_read: true,
								update_time:Date.now()
							}).catch(e => {
								console.error(e);
							})
						}
					}
				}
			},
			loadData(callback) {
				this.$refs.udb.loadData({
					clear: true //可选参数，是否清空数据
				}, (e) => {
					if (callback) {
						callback(e)
					}
				})
			},
			refresh(callback) {
				this.$refs.udb.loadData({
					clear: true //可选参数，是否清空数据
				}, (e) => {
					if (callback) {
						callback(e)
					}
				})
				// 刷新未读消息数
				uncUtils.refreshUnreadCount()
			},
			// 全部已读
			clearAllUnRead(){
				let unreadCount = uncUtils.unreadCounts
				for (let key in unreadCount) {
					unreadCount[key] = 0
				}
				uncUtils.unreadCounts = unreadCount
				db.collection('uni-notification-center')
					.where(`"is_read" == ${false} && "user_id" == $cloudEnv_uid`)
					.update({"is_read":true})
				
				let list = this.notificationList.filter(item=>{
					return item.to_all && item.is_read == false
				}).map(item=>{
					return {
						"notification_id":item._id,
						"user_id":uniCloud.getCurrentUserInfo().uid
					}
				})
				// console.log('list:',list);
				if(list.length){
					db.collection('uni-notification-read-log').add(list)
				}
				
				this.notificationList.forEach(item=>item.is_read = true)
			},
			clickSwiperItem(item){
				console.log(item);
				let {title,content} = item
				uni.showModal({
					title,content,
					showCancel: false,
					confirmText: '关闭'
				});
			},
			showMore(){
				uni.switchTab({
					url:'/uni_modules/uni-notification-center/pages/index/index',
					fail: (err) => {
						console.log(err);
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	/* #ifdef H5 */
	.root,.root *{
		max-width: 500px;
	}
	/* #endif */
	
	.segmented-control {
		position: absolute;
		width: 750rpx;
		background-color: #FFFFFF;
		top: 0;
		left: 0;
	}

	.main-container {
		padding-top: 46px;
	}
	
	.main-container-item {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
	}

	.item-type {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		padding: 5px 10px;
	}
	
	.title-box {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex: 1;
		padding: 5px 10px;
		flex-direction: row;
		justify-content: space-between;
	}
	
	.dateformat{
		color: #999999;
		font-size: 12px;
	}

	.content {
		padding: 5px 20px;
	}

	.dot-box {
		width: 10px;
		position: relative;
		left: 5px;
	}
	
	/* #ifndef APP-NVUE */
	.uni-notice-bar,
	.swiper,
	.swiper-item{
		display: flex;
	}
	/* #endif */
	.uni-notice-bar {
		background-color: #fff8e5;
		padding:0 6px;
		flex-direction: row;
		justify-content: center;
		align-items: center;
	}
	.swiper{
		flex: 1;
		padding:0 5px;
		/* border: 1px solid #000; */
		height: 35px;
		justify-content: center;
		align-items: center;
		align-content: center;
	}
	.swiper-item{
		height: 35px;
		font-size: 14px;
		color: #fd8734;
		align-items: center;
		/* border: 1px solid #000; */
	}
	/* #ifndef APP-NVUE */
	::v-deep .swiper-item span{
		overflow:hidden;  
		text-overflow:ellipsis;
		white-space: nowrap;
	}
	/* #endif */
	.show-more{
		font-size: 14px;
		color: #fd8734;
	}
</style>
